import React from 'react'
import { BaseListPage, columnRenders, http, IBaseListPageState, IBaseListPageProps, UdModal, UdModalForm, IUdFormItem, UdTable, UdDateRangePicker, UdDatePicker, validators, uaaApp } from '@/lib'
import { Button, Select, InputNumber, Input, Spin, Modal, message } from 'antd'
import apis from '@/apis/AboutQuota'
import comApis from '@/apis'
import dayjs from 'dayjs'
import udMainStore from '@/store/UdMain'
import UdSelect from '@/components/UdFormControls/UdSelect'
import { WrappedFormUtils } from 'antd/lib/form/Form'

const { Option } = Select
const { confirm } = Modal
const updateBtnAuth = 'quota_employee_manager_saveOrUpdateAssessSet'
const deleteBtnAuth = 'quota_employee_manager_delAssessSet'

class List extends BaseListPage<IQuotaAssessYearListProps, IQuotaAssessYearListState> {
  protected useConditionsField = true
  // 隐藏掉头曲二曲
  private hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  private brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  // private brandList = udMainStore.brandList
  private modalForm: WrappedFormUtils
  constructor(props) {
    super(props)
    this.state = {
      title: '配额考核年度设置',
      queryApi: apis.QuotaAssessYearConfigList,
      rowKey: 'id',
      conditions: [
        { label: '品牌公司', id: 'brandCode', render: <UdSelect options={this.brandList} /> },
        {
          label: '考核年度', id: 'year', render: () => <UdSelect options={this.state.assessYearList} showSearch={true} optionFilterProp='children' />
        },
      ],
      columns: [
        { title: '序号', dataIndex: 'no', render: (text, record, index) => index + 1 },
        { title: '品牌公司', dataIndex: 'brandName' },
        { title: '考核年度', dataIndex: 'year' },
        { title: '开始日期', dataIndex: 'startTime', render: (text) => text && dayjs(text).format('YYYY-MM-DD') },
        { title: '结束日期', dataIndex: 'endTime', render: (text) => text && dayjs(text).format('YYYY-MM-DD') },
        { title: '最近更新时间', dataIndex: 'updateTime' },
        { title: '最近更新人', dataIndex: 'updateName' },
        {
          title: '操作', dataIndex: 'operate', fixedWidth: '80px', render: columnRenders.operate([
            { title: '编辑', auth: updateBtnAuth, action: (text, record) => this.openModal(record) },
            { title: '删除', auth: deleteBtnAuth, action: (text, record) => this.deleteHandle(record) },
          ])
        },
      ],
      leftBtns: [
        uaaApp.canUse(updateBtnAuth) && <Button onClick={() => this.openModal()} type='primary'>创建考核年度</Button>,
      ],
      tableProps: {
        rowSelection: null,
      },
      assessYearList: [],
    }
  }

  componentDidMount() {
    super.componentDidMount()
    this.getAssessYearList()
  }

  public getAssessYearList = () => {
    http.get(comApis.GetQuotaAssessYearList).then(res => {
      const assessYearList = res.data?.map(({ year: value, name: title }) => ({ value, title })) || []
      this.setState({
        assessYearList,
      })
    })
  }

  public openModal = (row?) => {
    let title = row ? '编辑' : '创建'
    if (row) {
      row.brandCode = { key: row.brandCode, label: row.brandName }
    }
    UdModal.open({
      title: title + '考核年度',
      content: <UdModalForm getForm={(form) => this.modalForm = form} items={[
        { label: '品牌公司', id: 'brandCode', rules: [validators.required], render: <UdSelect labelInValue options={this.brandList} /> },
        { label: '考核年度', id: 'year', rules: [validators.required], render: <UdSelect options={this.state.assessYearList} /> },
        { label: '开始日期', id: 'startTime', rules: [validators.required, { validator: (rule, value, callback) => this.validatorModalTime('startTime', rule, value, callback) }], decoratorOptions: { getValueFromEvent: (date) => date && dayjs(date).format('YYYY-MM-DD 00:00:00') }, render: <UdDatePicker /> },
        { label: '结束日期', id: 'endTime', rules: [validators.required, { validator: (rule, value, callback) => this.validatorModalTime('endTime', rule, value, callback) }], decoratorOptions: { getValueFromEvent: (date) => date && dayjs(date).format('YYYY-MM-DD 23:59:59') }, render: <UdDatePicker /> },
      ]} values={row} />,
      onOk: (values) => {
        const params = values
        const { brandCode, startTime, endTime } = params
        if (dayjs(startTime).valueOf() > dayjs(endTime).valueOf()) {
          message.error('结束时间必须大于开始时间')
          return Promise.reject()
        }
        if (brandCode) {
          params.brandCode = brandCode.key
          params.brandName = brandCode.label
        }
        if (row && row.id) {
          // 修改
          params.id = row.id
        }
        return http.post(apis.UpdateQuotaAssessYear, params).then(res => {
          message.success('操作成功')
          this.query()
        })
      }
    })
  }

  private validatorModalTime = (key, rule, value, callback) => {
    if (key == 'startTime') {
      // 校验开始时间
      let endTime = this.modalForm.getFieldValue('endTime')
      if (endTime) {
        // 操作开始时间去触发校验结束时间是否满足条件
        this.modalForm.validateFields(['endTime'], { force: true })
      }
      callback()
    } else if (key == 'endTime') {
      // 校验结束时间
      let startTime = this.modalForm.getFieldValue('startTime')
      startTime = startTime && dayjs(startTime).valueOf()
      const endTime = value && dayjs(value).valueOf()
      if (startTime && startTime > endTime) {
        callback('结束时间必须大于开始时间')
      } else {
        callback()
      }
    }
  }

  public deleteHandle = (row) => {
    confirm({
      title: '确定要删除该数据吗？',
      onOk: () => {
        return http.get(apis.DeleteQuotaAssessYear, { params: { id: row.id } }).then(res => {
          message.success('删除成功')
          this.query()
        })
      }
    })
  }

}

export default List

interface IQuotaAssessYearListState extends IBaseListPageState {
  assessYearList: any[]
}

interface IQuotaAssessYearListProps extends IBaseListPageProps {

}

